using Lzfy_Refund_Service.Models;
using Lzfy_Refund_Service.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.ComponentModel.DataAnnotations;
using System.Security.Cryptography;
using System.Text;

namespace Lzfy_Refund_Service.Controllers
{
    /// <summary>
    /// 患者退费密码管理控制器
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    [Authorize]
    public class PatientRefundPasswordController : ControllerBase
    {
        private readonly IPatientRefundPasswordService _service;
        private readonly ILogger<PatientRefundPasswordController> _logger;

        public PatientRefundPasswordController(
            IPatientRefundPasswordService service,
            ILogger<PatientRefundPasswordController> logger)
        {
            _service = service;
            _logger = logger;
        }

        /// <summary>
        /// 更新患者退费密码相关信息
        /// </summary>
        /// <param name="request">更新请求</param>
        /// <returns>更新结果</returns>
        /// <response code="200">更新成功</response>
        /// <response code="400">请求参数无效</response>
        /// <response code="404">患者不存在</response>
        /// <response code="500">服务器内部错误</response>
        [HttpPost("update")]
        [ProducesResponseType(typeof(PatientRefundPasswordUpdateResponse), 200)]
        [ProducesResponseType(typeof(PatientRefundPasswordUpdateResponse), 400)]
        [ProducesResponseType(typeof(PatientRefundPasswordUpdateResponse), 404)]
        [ProducesResponseType(typeof(PatientRefundPasswordUpdateResponse), 500)]
        public async Task<ActionResult<PatientRefundPasswordUpdateResponse>> UpdatePatientRefundPassword(
            [FromBody] PatientRefundPasswordUpdateRequest request)
        {
            try
            {
                _logger.LogInformation("Received request to update patient refund password for PatientId: {PatientId}", request?.PatientId);

                if (request == null)
                {
                    _logger.LogWarning("Request body is null");
                    return BadRequest(new PatientRefundPasswordUpdateResponse
                    {
                        Success = false,
                        Message = "请求体不能为空"
                    });
                }

                // 验证模型
                if (!ModelState.IsValid)
                {
                    var errors = ModelState
                        .Where(x => x.Value?.Errors.Count > 0)
                        .SelectMany(x => x.Value!.Errors)
                        .Select(x => x.ErrorMessage)
                        .ToList();
                    
                    var errorMessage = string.Join("; ", errors);
                    _logger.LogWarning("Model validation failed: {Errors}", errorMessage);
                    
                    return BadRequest(new PatientRefundPasswordUpdateResponse
                    {
                        Success = false,
                        Message = $"请求参数验证失败: {errorMessage}",
                        PatientId = request.PatientId
                    });
                }

                var response = await _service.UpdatePatientRefundPasswordAsync(request);

                if (response.Success)
                {
                    return Ok(response);
                }
                else
                {
                    // 根据错误消息判断返回的状态码
                    if (response.Message.Contains("不存在"))
                    {
                        return NotFound(response);
                    }
                    else
                    {
                        return BadRequest(response);
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Unexpected error occurred while updating patient refund password");
                return StatusCode(500, new PatientRefundPasswordUpdateResponse
                {
                    Success = false,
                    Message = "服务器内部错误，请稍后重试"
                });
            }
        }

        /// <summary>
        /// 生成MD5哈希值
        /// </summary>
        /// <param name="input">要加密的字符串</param>
        /// <returns>MD5哈希值</returns>
        /// <response code="200">生成成功</response>
        /// <response code="400">请求参数无效</response>
        [HttpPost("md5")]
        [ProducesResponseType(typeof(Md5Response), 200)]
        [ProducesResponseType(typeof(Md5Response), 400)]
        public ActionResult<Md5Response> GenerateMd5([FromBody] Md5Request request)
        {
            try
            {
                if (request == null || string.IsNullOrEmpty(request.Input))
                {
                    return BadRequest(new Md5Response
                    {
                        Success = false,
                        Message = "输入字符串不能为空"
                    });
                }

                using (var md5 = MD5.Create())
                {
                    var inputBytes = Encoding.UTF8.GetBytes(request.Input);
                    var hashBytes = md5.ComputeHash(inputBytes);
                    var hash = Convert.ToHexString(hashBytes).ToLower();

                    return Ok(new Md5Response
                    {
                        Success = true,
                        Hash = hash,
                        Message = "MD5生成成功"
                    });
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error generating MD5 hash");
                return StatusCode(500, new Md5Response
                {
                    Success = false,
                    Message = "服务器内部错误"
                });
            }
        }
    }

    /// <summary>
    /// MD5请求模型
    /// </summary>
    public class Md5Request
    {
        /// <summary>
        /// 要加密的字符串
        /// </summary>
        [Required(ErrorMessage = "输入字符串不能为空")]
        public string Input { get; set; } = string.Empty;
    }

    /// <summary>
    /// MD5响应模型
    /// </summary>
    public class Md5Response
    {
        /// <summary>
        /// 是否成功
        /// </summary>
        public bool Success { get; set; }

        /// <summary>
        /// MD5哈希值
        /// </summary>
        public string? Hash { get; set; }

        /// <summary>
        /// 消息
        /// </summary>
        public string Message { get; set; } = string.Empty;
    }
}